<template>
  <view>
    <u-popup :show="show" :round="10" @close="cancel">
      <view class="header-wrap">
        <text>{{title}}</text>
        <uni-icons @click="cancel" type="closeempty" size="20px" color="#CCCCCC" />
      </view>
      <view style="padding: 20rpx">
        <uni-easyinput prefixIcon="search" v-if="showSearch" :maxlength="50" v-model="keyword" placeholder="请输入关键字"
          @clear="search" @input="search">
        </uni-easyinput>
        <u-gap v-if="showSearch" height="15"></u-gap>
        <scroll-view :scroll-top="scrollTop" scroll-y="true" class="scroll-Y" @scrolltolower="$emit('lower')">
          <!--单选-->
          <view v-if="type == 'radio'">
            <view class="list-item radio" :class="{'active-text':radioValue === item[value]}"
              v-for="(item, index) in dataLists" @click="radioChange(item)" :key="index">
              <text>{{ item[name] }}</text>
              <image v-if="radioValue === item[value]" :src="radioSelected"
                style="width: 30rpx; height: 30rpx;margin-right: 10px;">
              </image>
            </view>
          </view>

          <!--多选-->
          <view v-if="type == 'checkbox'">
            <view class="list-item checkbox" v-for="(item, index) in dataLists" @click="ckeckedChange(item)"
              :key="index">
              <image :src="
                  checkboxValue.includes(item[value]) ? checkImg : uncheckImg
                " style="width: 30rpx; height: 30rpx"></image>
              <text>{{ item[name] }}</text>
            </view>
          </view>
        </scroll-view>
        <u-gap height="45"></u-gap>
        <view class="bottons">
          <u-row>
            <u-col customStyle="padding:0 10rpx 20rpx 20rpx" class="cancel-btn" span="6">
              <button @click="cancel" type="default"
                style="color: #323233 !important;background: #ffffff !important;height: 40px;line-height: 40px;border:2rpx solid #E6E6E6!important;">
                取消
              </button>
            </u-col>
            <u-col customStyle="padding:0 20rpx 20rpx 10rpx" span="6">
              <u-button @click="submit" type="primary"
                :disabled="!radioValue && checkboxData.length === 0">确认</u-button>
            </u-col>
          </u-row>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
  /**
     * 公共选择下拉框，基于uview。支持下拉加载、列表搜索、单选｜多选
     * @author qianziyu
     * @description 弹出层选择器，基于uview中u-popup实现
     * @property {Array}			dataLists			数据列表
     * @property {String}			name				列表显示的字段名
     * @property {Boolean}			show				是否展示弹窗 (默认 false )
     * @property {String}			type				选择类型 单选｜多选 (默认 单选 )
     * @property {Boolean}			showSearch			是否显示搜索框 (默认 true )
     * @property {String}			placeholder			搜索框placeholder
     * @event {Function} search 搜索事件，返回keyword
     * @event {Function} lower 滑动到底部触发，用于下拉加载新数据
     * @event {Function} cancel 组件关闭事件
     * @event {Function} submit 提交按钮,返回选中的列表数据
     * @example <common-select :show="show" @cancel="show=false" @search="selectSearch" name="cworkStationName" @submit="onsubmit"
        :dataLists="dataLists" placeholder="输入工站名称搜索"></common-select>
     */
  import config from '@/config';

  export default {
    name: 'qianziyu-select',
    props: {
      dataLists: {
        default: {},
        type: Array
      },
      name: {
        default: 'name'
      },
      title: {
        default: '选择客户',
        type: String
      },
      value: {
        default: 'value'
      },
      type: {
        default: 'radio',
        type: String
      },
      showSearch: {
        default: true,
        type: Boolean
      },
      placeholder: {
        default: '请输入搜索内容'
      },
      param: {
        default: ''
      },
      params: {
        type: Array,
        default: []
      },
      show: {
        type: Boolean,
        default: false
      }
    },
    watch: {
      param: {
        handler(value) {
          this.$nextTick(() => {
            this.radioData = this.dataLists.find((e) => e[this.value] === value);
            if (!this.radioData) {
              this.$nextTick(() => {
                this.dataLists.forEach((e, index) => {
                  e['isChecked'] = false;
                  this.$set(this.dataLists, index, e);
                });
              })
            }
            this.radioValue = this.radioData?.[this.value]
          })
        },
        immediate: true,
        deep: true
      },
      params: {
        handler(value) {
          if (!value.length) {
            return;
          }
          this.$nextTick(() => {
            this.checkboxValue = value.map((e) => e.value);
            this.dataLists = this.dataLists.map((e) => {
              if (this.checkboxValue.includes(e[this.value])) {
                e['isChecked'] = true;
              }
              return e;
            });
            this.checkboxData = this.dataLists.filter((e) => e.isChecked);
          })
        },
        immediate: true,
        deep: true
      }
    },
    computed: {
      radioSelected() {
        return config.baseImgUrl + '/radio-selected.png';
      },
      checkImg() {
        if (this.$store.state.user.curTypeColor == '#D22C2C') {
          return config.baseImgUrl + '/checked1.png';
        } else if (this.$store.state.user.curTypeColor == '#409EFE') {
          return config.baseImgUrl + '/checked.png';
        } else {
          return config.baseImgUrl + '/checked.png';
        }
      },
      uncheckImg() {
        return config.baseImgUrl + '/unchecked.png';
      }
    },
    data() {
      return {
        keyword: '',
        scrollTop: 0,
        checkboxData: [],
        checkboxValue: [],
        radioData: {},
        radioValue: ''
      };
    },
    onShow() {
    },
    methods: {
      ckeckedChange(data) {
        if (data.isChecked) {
          data['isChecked'] = false;
        } else {
          data['isChecked'] = true;
        }
        this.checkboxData = [];
        this.checkboxData = this.dataLists.filter((e) => e.isChecked);
        this.checkboxValue = this.checkboxData.map((e) => e[this.value]);
      },
      //选择列表项触发
      radioChange(data) {
        this.radioValue = data[this.value];
      },
      //点击搜索触发
      search() {
        this.scrollTop = 0
        this.radioData = {}
        this.radioValue = ''
        this.checkboxData = []
        this.checkboxValue = []
        this.$emit('search', this.keyword);
      },
      //点击取消按钮触发
      cancel() {
        this.keyword = '';
        if (this.radioData && Object.keys(this.radioData).length) {
          this.radioValue = this.radioData[this.value]
        } else {
          this.radioValue = ''
        }
        this.$emit('cancel');
      },
      //提交触发
      submit() {

        if (this.type == 'radio') {
          if (!this.radioValue) {
            uni.$u.toast('请选择数据');
            return;
          }
          this.radioData = this.dataLists.find(
            (e) => e[this.value] == this.radioValue
          );
          this.$emit('submit', this.radioData);
        } else if (this.type == 'checkbox') {
          if (this.checkboxData.length == 0) {
            return;
          }
          this.$emit('submit', this.checkboxData);
        }
        this.keyword = '';
      },
      resetData() {
        this.keyword = ''
        this.scrollTop = 0
        this.checkboxData = []
        this.checkboxValue = []
        this.radioData = {}
        this.radioValue = ''
      },
    }
  };
</script>

<style lang="scss" scoped>
  .header-wrap {
    position: relative;
    height: 47px;
    padding: 12px;
    text-align: center;
    border-bottom: 1px solid #EAEAEA;

    text {
      font-size: 16px;
      font-weight: 600;
    }

    uni-icons {
      position: absolute;
      right: 18px;
    }
  }


  .scroll-Y {
    height: 650rpx;
  }

  .bottons {
    background-color: white;
    position: fixed;
    left: 0;
    bottom: 0;
    right: 0;
    bottom: constant(safe-area-inset-bottom);
    bottom: env(safe-area-inset-bottom);
  }

  .list-item {
    border-bottom: 1px solid #eaeaea;
    height: 50px;
    font-size: 15px;
    font-weight: 500;

    text {
      margin-left: 6px;
    }
  }

  .list-item.radio {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .list-item.checkbox {
    display: flex;
    align-items: center;
  }

  .active-text {
    color: #409EFE !important;
  }

  ::v-deep button {
    font-size: 15px !important;
  }
</style>